﻿// (c) Copyright slimCODE Software Inc. - www.slimcode.com
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using SlimCode.Windows.Forms.Mobile;
using SlimCode.Windows.Controls.Mobile;
using System.Runtime.InteropServices;

namespace SlimCode.SlimPasswords
{
  internal partial class SearchPasswordScreen : UserControl, IScreen
  {
    private IScreenHost m_host;

    public SearchPasswordScreen()
    {
      InitializeComponent();

      searchButton.SetItem( new ItemView( searchButton.Text ) );
    }

    private void UpdateList()
    {
      if( Program.ActiveStore == null )
      {
        foundList.Items.Clear();
        foundList.Items.Add( new ItemView( 
          "No password store loaded or created. Open an existing or create a new password store by pressing \"More\" : \"Load or Create\".", 
          ContentAlignmentEx.TopLeft, 
          6 ) );
      }
      else
      {
        foundList.SuspendUpdate();

        try
        {
          foundList.Items.Clear();

          // TODO: Is this still necessary? It was to fix a bug.
          foundList.SetOffset( new Point( 0, 0 ), false );

          int count = 0;
          int lastStrength = 0;
          List<PasswordItem> overflow = new List<PasswordItem>();

          Program.ActiveStore.UpdateStrengths( searchTextBox.Text );

          foreach( ItemStrength item in Program.ActiveStore.Strengths )
          {
            count++;

            if( ( item.Strength == 0 ) && ( searchTextBox.TextLength > 0 ) )
            {
              // Only when the search box is empty do we keep non-matching items.
              break;
            }

            if( ( overflow.Count > 0 )
              || ( ( count > 20 ) && ( item.Strength < lastStrength ) )
              || ( count > 40 ) )
            {
              overflow.Add( item.Item as PasswordItem );
            }
            else
            {
              foundList.Items.Add( new PasswordView( item.Item as PasswordItem ) );
            }

            lastStrength = item.Strength;
          }

          if( ( foundList.Items.Count == 0 ) && ( searchTextBox.TextLength > 0 ) )
          {
            foundList.Items.Add( new ItemView(
              "No password entry found matching your search criteria.", 
              ContentAlignmentEx.TopLeft, 
              6 ) );
          }
          else if( overflow.Count > 0 )
          {
            foundList.Items.Add( new ShowMoreView( overflow ) );
          }
        }
        finally
        {
          foundList.ResumeUpdate();
        }
      }
    }

    private void searchTextBox_TextChanged( object sender, EventArgs e )
    {
      if( ( Program.Settings.AutoUpdateCharCount > 0 ) && ( searchTextBox.Text.Length >= Program.Settings.AutoUpdateCharCount ) )
      {
        this.UpdateList();
      }
    }

    private void loadMenuItem_Click( object sender, EventArgs e )
    {
      if( m_host != null )
      {
        SelectStoreScreen screen = new SelectStoreScreen();

        screen.StoreFilename = Program.Settings.LastStore;

        m_host.ShowScreen( screen );
      }
    }

    private void exitMenuItem_Click( object sender, EventArgs e )
    {
      Application.Exit();
    }

    private void searchTextBox_KeyPress( object sender, KeyPressEventArgs e )
    {
      if( e.KeyChar == '\r' )
      {
        e.Handled = true;
        this.UpdateList();
      }
    }

    private void searchButton_Click( object sender, EventArgs e )
    {
      this.UpdateList();
    }

    private void foundList_ItemClick( object sender, ItemEventArgs args )
    {
      if( m_host != null )
      {
        PasswordView view = args.Item as PasswordView;

        if( view != null )
        {
          m_host.ShowScreen( new PasswordItemScreen( view.Item ) );
        }
        else
        {
          ShowMoreView showMoreView = args.Item as ShowMoreView;

          if( showMoreView != null )
          {
            foundList.SuspendUpdate();

            try
            {
              foundList.Items.Remove( showMoreView );

              foreach( PasswordItem item in showMoreView.RemainingItems )
              {
                foundList.Items.Add( new PasswordView( item ) );
              }
            }
            finally
            {
              foundList.ResumeUpdate();
            }
          }
        }
      }
    }

    private void addMenuItem_Click( object sender, EventArgs e )
    {
      if( m_host != null )
      {
        if( Program.ActiveStore != null )
        {
          m_host.ShowScreen( new EditPasswordItemScreen( new PasswordItem( Program.ActiveStore ), true ) );
        }
      }
    }

    private void optionsMenuItem_Click( object sender, EventArgs e )
    {
      if( m_host != null )
      {
        m_host.ShowScreen( new OptionsScreen() );
      }
    }

    private void aboutMenuItem_Click( object sender, EventArgs e )
    {
      if( m_host != null )
      {
        m_host.ShowScreen( new AboutScreen() );
      }
    }

    private void AnyControl_GotFocus( object sender, EventArgs e )
    {
      if( m_host != null )
      {
        Program.ToggleInputPanelIf( m_host.MainForm.MainInputPanel, ( sender is TextBox ) );
      }
    }

    #region IScreen Members

    public Control Control
    {
      get { return this; }
    }

    public Control DefaultFocus
    {
      get { return searchTextBox; }
    }

    public MainMenu Menu
    {
      get { return mainMenu; }
    }

    public string Title
    {
      get { return "slimPASSWORDS - Search"; }
    }

    public bool Hiding( DialogResult result )
    {
      return true;
    }

    public void HidingChild( IScreen child, DialogResult result )
    {
      if( result == DialogResult.OK )
      {
        EditPasswordItemScreen editScreen = child as EditPasswordItemScreen;

        if( editScreen != null )
        {
          if( editScreen.IsNew )
          {
            Program.ActiveStore.AddPasswordItem( editScreen.Item );
          }

          Program.SaveStore( Program.ActiveStore, m_host );
        }

        this.UpdateList();
      }
    }

    public void Showing( IScreenHost host )
    {
      m_host = host;
      this.UpdateList();
    }

    #endregion

    private void foundList_ItemSlide( object sender, ItemSlideEventArgs args )
    {
      if( m_host != null )
      {
        PasswordView passwordView = args.Item as PasswordView;

        if( passwordView != null )
        {
          if( args.SlidingOffset.X < 0 )
          {
            if( MessageBox.Show(
              string.Format( "Do you really want to delete password entry '{0}'?", passwordView.Item.Title ),
              "Confirm",
              MessageBoxButtons.YesNo,
              MessageBoxIcon.Question,
              MessageBoxDefaultButton.Button1 ) == DialogResult.Yes )
            {
              Program.ActiveStore.DeletePasswordItem( passwordView.Item );
              Program.SaveStore( Program.ActiveStore, m_host );

              this.UpdateList();
            }
          }
          else
          {
            m_host.ShowScreen( new EditPasswordItemScreen( passwordView.Item, false ) );
          }
        }
      }
    }
  }
}
